package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.Admin;
import com.example.crossborderecommerce.entity.ProductAttribute;
import com.example.crossborderecommerce.entity.ProductCategory;
import com.example.crossborderecommerce.entity.Result;
import com.example.crossborderecommerce.mapper.ProductAttributeMapper;
import com.example.crossborderecommerce.service.IAdminService;
import com.example.crossborderecommerce.service.IProductAttributeService;
import com.example.crossborderecommerce.service.IProductCategoryService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品属性模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/product-attribute")
public class ProductAttributeController {
    @Resource
    IProductAttributeService productAttributeService;
    @Resource
    IProductCategoryService productCategoryService;
    @Resource
    IAdminService adminService;
    @Resource
    ProductAttributeMapper productAttributeMapper;

    /**
     * 添加产品属性
     * @param productAttribute
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody ProductAttribute productAttribute){
        boolean res = productAttributeService.save(productAttribute);
        if(res){
            return Result.success("添加产品属性成功！");
        }
        return Result.error("添加产品属性失败！");
    }

    /**
     * 删除产品属性
     * @param productAttribute
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody ProductAttribute productAttribute){
        boolean res = productAttributeService.removeById(productAttribute);
        if (res){
            return Result.success("删除产品属性成功！");
        }
        return Result.error("删除产品属性失败！");
    }

    /**
     * 删除一系列产品属性
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> productAttributeIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = productAttributeService.removeByIds(productAttributeIds);
        if(res) {
            return Result.success("删除产品分类成功！");
        }
        return Result.error("删除产品分类失败！");
    }

    /**
     * 修改产品属性
     * @param productAttribute
     * @return
     */
    @PostMapping("/updateAttribute")
    public Result updateAttribute(@RequestBody ProductAttribute productAttribute) {
        boolean res = productAttributeService.updateAttribute(productAttribute);
        if (res) {
            return Result.success("修改产品属性成功！");
        }
        return Result.error("修改产品属性失败！");
    }

    /**
     * 以列表形式返回所有的产品属性
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<ProductAttribute> productAttributeList = productAttributeService.list();
        if(productAttributeList == null) {
            return Result.error("获取全部产品类别失败！");
        }
        for(ProductAttribute productAttribute : productAttributeList) {
            if(productAttribute.getCategoryId() != null) {
                ProductCategory productCategory1 = productCategoryService.getById(productAttribute.getCategoryId());
                productAttribute.setCategoryName(productCategory1.getName());
            }
        }
        return Result.success("获取全部产品类别成功！", productAttributeList);
    }

    /**
     * 获取全部产品属性
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam(defaultValue = "-1") String adminId){
        Page<ProductAttribute> productAttributePage = productAttributeService.page(new Page<>(pageNum,pageSize));
        List<ProductAttribute> productAttributeList = productAttributeMapper.getProductAttributeByPage(productAttributePage, adminId);
        for(ProductAttribute productAttribute : productAttributeList) {
            Admin admin = adminService.getById(productAttribute.getAdminId());
            productAttribute.setAdminName(admin.getName());
            if(productAttribute.getCategoryId() != null) {
                ProductCategory productCategory1 = productCategoryService.getById(productAttribute.getCategoryId());
                productAttribute.setCategoryName(productCategory1.getName());
            }
        }
        Page<ProductAttribute> newProductAttributePage = new Page<>(pageNum, pageSize);
        newProductAttributePage.setRecords(productAttributeList);
        newProductAttributePage.setTotal(productAttributePage.getTotal());
        return Result.success("成功查询所有产品属性！",newProductAttributePage);
    }
    /**
     * 查询产品属性中所有创建人
     * @return
     */
    @GetMapping("/findAdminsInProductAttribute")
    public Result findAdminsInProductAttribute() {
        List<Admin> adminList = productAttributeService.findAdminsInProductAttribute();
        if(adminList == null) {
            return Result.error("获取管理员信息失败！");
        }
        return Result.success(adminList);
    }
    /**
     * 导出产品属性
     * @param adminId
     * @param response
     * @return
     */
    @GetMapping("exportProductAttributeList")
    public Result exportProductAttributeList(@RequestParam(defaultValue = "-1") String adminId,
                                            HttpServletResponse response) {
        List<ProductAttribute> productAttributeList = productAttributeMapper.getProductAttribute(adminId);
        for(ProductAttribute productAttribute : productAttributeList) {
            Admin admin = adminService.getById(productAttribute.getAdminId());
            productAttribute.setAdminName(admin.getName());
            if(productAttribute.getCategoryId() != null) {
                ProductCategory productCategory1 = productCategoryService.getById(productAttribute.getCategoryId());
                productAttribute.setCategoryName(productCategory1.getName());
            }
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("分类名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("产品规格");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("产品颜色");
        cell.setCellStyle(style);
        cell = row.createCell((short) 4);
        cell.setCellValue("产品材质");
        cell.setCellStyle(style);
        cell = row.createCell((short) 5);
        cell.setCellValue("创建人");
        cell.setCellStyle(style);
        cell = row.createCell((short) 6);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < productAttributeList.size(); i++) {
            row = sheet.createRow(i + 1);
            ProductAttribute productAttribute = productAttributeList.get(i);
            row.createCell((short) 0).setCellValue(productAttribute.getId());
            if(productAttribute.getCategoryId() != null) {
                row.createCell((short) 1).setCellValue(productAttribute.getCategoryName());
            }
            else {
                row.createCell((short) 1).setCellValue("无");
            }
            row.createCell((short) 2).setCellValue(productAttribute.getSpecification());
            row.createCell((short) 3).setCellValue(productAttribute.getColor());
            row.createCell((short) 4).setCellValue(productAttribute.getMaterial());
            row.createCell((short) 5).setCellValue(productAttribute.getAdminName());
            try {
                Date createTime = inputDateFormat.parse(productAttribute.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 6).setCellValue(outputDateFormat.format(createTime));
            } catch (ParseException e) {
                row.createCell((short) 6).setCellValue(productAttribute.getCreateTime().toString());
            }
        }
        String fileName = "exportProductAttributeList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportProductAttributeList");
    }
}
